<template>
  <el-dialog v-if="load" :close-on-click-modal="false" :title="isLook ? '查看' : form.basic.pd_id ? '编辑' : '添加'"
    class="full" v-model="visible" align-center :z-index="2000" width="96%" @close="handleClose">
    <div class="flex flex-col h-full demand-demand" v-loading="loadings.detail"
      >
      <el-form v-if="visible" ref="formRef" :model="form" :validate-on-rule-change="false" :label-width="100"
        :label-position="isLook ? 'right' : 'top'" class="h-full w-full">
        <el-tabs v-if="isLook" v-model="activeName" class="-mt-2">
          <el-tab-pane label="基础信息" name="basic">
            <Sku ref="skuRef" v-model="form" :isLook="isLook" :options="options">
              <Basic v-model="form" :isLook="isLook" :options="options" />
            </Sku>
          </el-tab-pane>
          <el-tab-pane label="操作日志" name="log">
            <div class="v-title mb-3">操作日志</div>
            <div :style="{height: `calc(100% - 40px)`}">
              <vxe-table :data="form.log" height="auto" size="small">
                <vxe-column title="操作人" field="create_user"></vxe-column>
                <vxe-column title="操作类型" field="log_type"></vxe-column>
                <vxe-column title="详情" field="log_info" min-width="300"></vxe-column>
                <vxe-column title="操作时间" field="create_time"></vxe-column>
              </vxe-table>
            </div>
          </el-tab-pane>
        </el-tabs>
        <template v-else>
          <Basic v-model="form" :isLook="isLook" :options="options" />
          <Sku ref="skuRef" v-model="form" :isLook="isLook" :options="options" />
        </template>
      </el-form>
    </div>

    <template #footer>
      <VAudit :auth="(options.batch_audit_status || []).map(d => d.auth)" field="pd_id"
        url="/v1/purchase-demand/purchase-demand/batch-audit"
        :rows="[{ pd_id: form.basic.pd_id, demand_status: form.basic.demand_status }]"
        :list="options.batch_audit_status.filter(d => d.value === form.basic.demand_status)" statusField="demand_status"
        type="primary" />
      <template v-if="isLook">
        <el-button @click="close">关 闭</el-button>
        <template v-if="form.basic.demand_status === 9">
          <el-button type="primary" @click="() => skuRef.handleBatch('change')">批量变更</el-button>
          <el-button @click="() => skuRef.handleBatch('skuCancel')">批量取消订单</el-button>
        </template>
      </template>

      <template v-else>
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :loading="loadings.create2" @click="create(2)">保 存</el-button>
        <el-button type="primary" :loading="loadings.create1" @click="create(1)">提 交</el-button>
      </template>
    </template>
  </el-dialog>
</template>

<script setup>
import api from '../api'
import { ElMessage, ElMessageBox } from 'element-plus'
import Basic from './Basic'
import Sku from './Sku'
import XEUtils from 'xe-utils'

const props = defineProps({
  options: { type: Object, default: () => ({}) },
})
const emit = defineEmits(['close', 'success'])

const load = ref(false)
const addLoad = ref(false)
const visible = ref(false)
const isLook = ref(false)
const activeName = ref('basic')
let loadings = reactive({})

// 表单处理
const formRef = ref()
const form = ref({})
const skuRef = ref({})

// 打开弹窗
const success = ref(false)
const open = async (pd_id, look) => {
  success.value = false
  activeName.value = 'basic'
  isLook.value = look
  form.value = {
    basic: {},
    sku: [],
    log: []
  }
  if (!load.value) {
    load.value = true
    await 1
  }
  const { userInfo } = window
  form.value = {
    basic: {
      demand_type: 1,
      is_feishu_audit: 2,
      create_user_id: userInfo?.user?.user_id,
      create_user_name: userInfo?.user?.en_name,
      create_time: XEUtils.toDateString(new Date(), 'yyyy-MM-dd HH:mm:ss'),
      department_id: userInfo?.departments[0]?.department_id,
      department_name: userInfo?.departments[0]?.name
    },
    sku: [],
  }
  // 编辑
  if (pd_id) {
    loadings.detail = true
    const res = await api.detail({ pd_id })
    loadings.detail = false
    form.value = res.data
  }
  loadings = reactive({})
  visible.value = true
  formRef?.value?.resetFields()
  await nextTick()

  skuRef?.value.query()
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
  success.value && emit('success')
}
// 提交
const create = async (is_submit) => {
  const validator = await formRef?.value?.validate()
  if (!validator) return
  loadings['create' + is_submit] = true
  form.value.basic.is_submit = is_submit
  if (form.value.basic.demand_type === 1) {
    form.value.sku.forEach(d => {
      d.asin = ''
    })
  }
  api[form.value.basic.pd_id ? 'edit' : 'create'](form.value).then(res => {
    const { code, data, message } = res
    const { is_skip } = data
    if (code === 200) {
      ElMessage.success('保存成功')
      success.value = true
      close()
      return
    }
    if (is_skip === 2) {
      ElMessageBox.confirm(message, '提示', {
        type: 'error', confirmButtonText: '是',
        cancelButtonText: '否'
      }).then(res => {
        form.value.basic.is_skip = 2
        create(is_submit)
      }).finally(() => {
        loadings['create' + is_submit] = false
      })
    } else {
      ElMessage.error(message)
      loadings['create' + is_submit] = false
    }
  })
}

defineExpose({ open })
</script>

<style lang="scss">
.demand-demand {
  .el-tabs {
    height: 100%;
  }

  .el-tabs__content {
    height: calc(100% - 36px);
  }

  .el-tab-pane {
    height: 100%;
  }

  .vx-table__form-handle {
    display: none;
  }

  .vxe-pager {
    display: none;
  }
}
</style>